package com.captjack.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * <p>
 * ----------------------------------------------------------------------------- <br>
 * project name ：micro-service <br>
 * function：CcStringUtils <br>
 * description：CcStringUtils <br>
 * ----------------------------------------------------------------------------- <br>
 * change history <br>
 * <table width="432" border="1">
 * <tr>
 * <td>version</td>
 * <td>time</td>
 * <td>author</td>
 * <td>change</td>
 * </tr>
 * <tr>
 * <td>1.0.0</td>
 * <td>2018/9/20 14:06</td>
 * <td>Jack Sparrow</td>
 * <td>create</td>
 * </tr>
 * </table>
 * <br>
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2018/9/20 14:06
 * package com.captjack.common.util
 */
public final class CcStringUtils {

    /**
     * 替换内容
     */
    public static String replaceContent(String template, Map<String, Object> message) {
        return replaceContent(template, message, StringUtils.EMPTY, StringUtils.EMPTY);
    }

    /**
     * 根据key-value替换字符串中的内容
     *
     * @param template 模版
     * @param message  消息json
     * @return 替换后的内容
     */
    public static String replaceContent(String template, Map<String, Object> message, String keyPrefix, String keySuffix) {
        StringBuilder result = new StringBuilder(template);
        for (Map.Entry<String, Object> msg : message.entrySet()) {
            // 需要替换的内容key
            String needReplaceText = keyPrefix + msg.getKey() + keySuffix;
            int index = result.indexOf(needReplaceText);
            // 执行替换内容
            if (index > 0) {
                result.replace(index, index + needReplaceText.length(), msg.getValue().toString());
            }
        }
        return result.toString();
    }

    /**
     * 统计指定字符串在另一字符串中出现的次数
     * 注：此函数不重复计算，例：传入参数("1111", "11")，那么会返回2而非3
     *
     * @param nativeString        统计串
     * @param needStatisticString 匹配串
     * @return 总数
     */
    public static int getCharSequenceTotalCount(String nativeString, String needStatisticString) {
        if (nativeString == null || needStatisticString == null) {
            return 0;
        }
        if (nativeString.equals(needStatisticString)) {
            return 1;
        }
        // 总出现次数，需要查找字符串的长度，每次查找开始索引
        int totalCount = 0, needStatisticStringLength = needStatisticString.length(), tempIndex = -needStatisticStringLength;
        // 遍历直至不存在为止
        while ((tempIndex = nativeString.indexOf(needStatisticString, tempIndex + needStatisticStringLength)) != -1) {
            totalCount += 1;
        }
        return totalCount;
    }

    private CcStringUtils() {

    }

}
